#include "main.h"
#include <stdio.h>
#include <stdint.h>
#include "Drv_led.h"

#include "bsp_systick.h"
#include "bsp_task.h"
#include "bsp_key.h"

void HardWare_Init(void)
{
	//SystemInit();
	SysTick_Init(1);
	LED_Init();
	Key_Init();
}

extern uint8_t key1_pressflag;
extern uint8_t key2_pressflag;
extern uint8_t key3_pressflag;
void user_func(void){
    static uint32_t loc_mill;
    static uint32_t change_time = 100;

    if(SYSTICK_GetTime_Ms() - loc_mill < change_time){
        return;
    }
    loc_mill = SYSTICK_GetTime_Ms();

    static bool direction = false;

    bool led_state[3];
    static uint8_t water_position = 1;
    for(int i = 0; i < 3; i++){
        led_state[i] = (water_position == i);
    }

    water_position = (direction ? (water_position + 1) : (water_position - 1)) % 3;

    for(int i = 0; i < 3; i++){
        if(led_state[i]) Drv_LED_ON(i);
        else Drv_LED_OFF(i);
    }

    static uint8_t last_key1_pressflag = 0, last_key2_pressflag = 0, last_key3_pressflag = 0;

    if(last_key1_pressflag == 0 && key1_pressflag == 1){
        direction = !direction;
    }

    if((key2_pressflag == 1) && (last_key2_pressflag == 0)){
        change_time += 100;
    }

    if((key3_pressflag == 1) && (last_key3_pressflag == 0)){
        change_time = (change_time == 100) ? 100 : change_time - 100;
    }
    
    last_key1_pressflag = key1_pressflag;
    last_key2_pressflag = key2_pressflag;
    last_key3_pressflag = key3_pressflag;
}

/**
*/
int main(void)
{
	HardWare_Init();
	Scheduler_Setup();
	
    while (1)
    {
		Scheduler_Run();
	    user_func();
        //SysTick_DelayMS(1);
    }
}

/**
 * @brief Assert failed function by user.
 * @param file The name of the call that failed.
 * @param line The source line number of the call that failed.
 */
#ifdef USE_FULL_ASSERT
void assert_failed(const uint8_t* expr, const uint8_t* file, uint32_t line)
{
    while (1)
    {
    }
}
#endif // USE_FULL_ASSERT





